import React, { useMemo, useState,useEffect } from 'react';
import { nanoid } from 'nanoid';
import Footer from './footer';
import LiItem from './liItem';
import './mainList.scss';

export default function MainList() {
	let [list, setList] = useState([
		{ id: 1, content: 'default,content', completed: false },
	]);
	let [listState, setlistState] = useState('all');
	let total = useMemo(
		() => list.filter((item) => !item.completed).length,
		[list]
	);
	let [showList, setShowList] = useState([]);


	useEffect(() => {
		setShowList(list.map(item => item))
	},[list])
	
	const handleListStateChanged = (status) => {
		switch (status) {
			case 'all':
				setShowList(list.map(item => item));break;
			case 'actived':
				setShowList(list.filter((item) => !item.completed));break;
			case 'completed':
				setShowList(list.filter((item) => item.completed));break;
			default:
				setShowList([]);
		}
		setlistState(status)
	};

	const hanleKeyUp = (e) => {
		const value = e.target.value.trim();
		if (e.key === 'Enter' && value) {
			setList([{ id: nanoid(), content: value, completed: false }, ...list]);
			e.target.value = '';
		}
	};

	const handleDelete = (index) => {
		list.splice(index, 1);
		setList([...list]);
	};

	const triggerItemRecord = (index) => {
		list[index].completed = !list[index].completed;
		setList([...list]);
	};

	return (
		<div className="main-todo">
			<input
				type="text"
				placeholder="what do want to do?"
				className="add-todo"
				autoFocus
				onKeyUp={(e) => hanleKeyUp(e)}
			/>
			<ul>
				{showList.map((item, index) => {
					return (
						<LiItem
							key={item.id}
							content={item.content}
							index={index}
							item={item}
							deleteRecord={handleDelete}
							triggerItemComlete={triggerItemRecord}
						/>
					);
				})}
			</ul>
			<Footer
				left={total}
				handleListStateChanged={handleListStateChanged}
				listState={listState}
			/>
		</div>
	);
}
